package org.springblade.modules.notice.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.CustomizableThreadFactory;
import java.util.concurrent.*;

/**
 * @Author ysq
 * @Date 2024/12/02
 * @Description 消息通知线程池配置
 */
@Configuration
public class NoticeTaskExecutorConfig {

	/**
	 * 核心线程数
	 */
	public static final int CORE_SIZE = 2;
	/**
	 * 最大线程数
	 */
	public static final int MAX_SIZE = 4;
	/**
	 * 线程最大空闲时间
	 */
	public static final int KEEP_ALIVE_SECONDS = 60;
	/**
	 * 队列容量
	 */
	public static final int QUEUE_CAPACITY = 100;
	/**
	 * 线程池名称前缀
	 */
	public static final String THREAD_NAME_PREFIX = "NoticeTask-";

	@Bean
	public Executor noticeTaskExecutor() {
		// 指定线程组名称，方便定位问题及线程池使用分析
		ThreadFactory threadFactory =  new CustomizableThreadFactory(THREAD_NAME_PREFIX);
		return new ThreadPoolExecutor(
			CORE_SIZE,
			MAX_SIZE,
			KEEP_ALIVE_SECONDS,
			TimeUnit.SECONDS,
			new LinkedBlockingQueue<>(QUEUE_CAPACITY),
			threadFactory,
			new ThreadPoolExecutor.CallerRunsPolicy()  //线程池无法继续接收任务时，让提交任务的主线程来执行任务
		);
	}
}
